package com.example.netchat;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;

public final class Datastore {
	private static final String ROOM_KIND = "rooms";
	private static final String PROP_ROOM_NAME = "room_name";
	private static final String PARTICIPANT_KIND = "participant";
	private static final String PROP_ROOM_ID = "room_id";
	private static final String PROP_REG_ID = "reg_id";

	private Datastore() {
		throw new UnsupportedOperationException();
	}

	public static String createRoom(String roomName) {
		DatastoreService service = DatastoreServiceFactory
				.getDatastoreService();

		Entity newRoom = new Entity(ROOM_KIND);
		newRoom.setProperty(PROP_ROOM_NAME, roomName);

		service.put(newRoom);

		return Long.toString(newRoom.getKey().getId());
	}

	public static void leaveRoom(long roomId, String regId) {
		DatastoreService service = DatastoreServiceFactory
				.getDatastoreService();

		Query query = new Query(PARTICIPANT_KIND);

		FilterPredicate roomFilter = new FilterPredicate(PROP_ROOM_ID,
				FilterOperator.EQUAL, roomId);
		FilterPredicate regIdFilter = new FilterPredicate(PROP_REG_ID,
				FilterOperator.EQUAL, regId);
		query.setFilter(CompositeFilterOperator.and(roomFilter, regIdFilter));

		List<Key> keys = new ArrayList<Key>();
		for (Entity entity : service.prepare(query).asIterable()) {
			keys.add(entity.getKey());
		}

		service.delete(keys);
	}

	public static void joinRoom(long roomId, String regId) {
		DatastoreService service = DatastoreServiceFactory
				.getDatastoreService();

		Entity entity = service.prepare(
				new Query(ROOM_KIND).setFilter(CompositeFilterOperator.and(
						new FilterPredicate(PROP_ROOM_ID, FilterOperator.EQUAL,
								Long.toString(roomId)), new FilterPredicate(
								PROP_REG_ID, FilterOperator.EQUAL, regId))))
				.asSingleEntity();

		if (entity == null) {
			entity = new Entity(PARTICIPANT_KIND);

			entity.setProperty(PROP_ROOM_ID, roomId);
			entity.setProperty(PROP_REG_ID, regId);
			service.put(entity);
		}
	}

	public static List<String> getParticipants(long roomId) {
		DatastoreService service = DatastoreServiceFactory
				.getDatastoreService();

		Query query = new Query(PARTICIPANT_KIND);

		FilterPredicate roomFilter = new FilterPredicate(PROP_ROOM_ID,
				FilterOperator.EQUAL, roomId);
		query.setFilter(roomFilter);
		List<String> regs = new ArrayList<String>();

		for (Entity entity : service.prepare(query).asIterable()) {
			regs.add((String) entity.getProperty(PROP_REG_ID));
		}

		return regs;
	}
}
